<template>
  <view class="container">


    <view class="top_box">
      <view class="top_box_info">
        <view class="top_box_info_picdiv">

          <view style="height: 100rpx;">


            <button open-type="chooseAvatar" class="top_box_info_picdiv_pic" :style="'border-color: var(--lv'+grade+')'"
              @chooseavatar="uploadPor">
              <image :src="portrait" class="refreshIcon"></image>
            </button>
            <view class="top_box_info_picdiv_level" :style="'background-color: var(--lv'+grade+')'">

              LV{{grade}}
            </view>
          </view>


          <view class="top_box_info_name">
            <view class="top_box_info_name_text" :style="'color: var(--lv'+grade+')'">
              {{info.nickname}}
              <text class="top_box_info_name_loc">{{info.province+info.city+info.district}}</text>

            </view>
            <view class="top_box_info_name_date">
              uid：<text selectable>{{info.id}}</text>


            </view>

          </view>
        </view>

        <view class="top_box_info_logo">

          <image :src="top_box_logo" @click="removeSto" style="height: 90rpx;width: 90rpx;" />
        </view>
        <!-- <button class="button" type="primary" @click="toggle('bottom')"><text class="button-text">底部</text></button> -->
      </view>
      <view class="info_box">
        <view class="pop_info" @tap="nameDialogToggle">
          <view class="title">
            <uni-icons type="person" size="25" color="#cb4f20"></uni-icons>
            <text>昵称</text>
          </view>
          <view class="info_text">

            <text>{{info.nickname}}</text>
            <uni-icons type="forward" size="15" color="#bebebe"></uni-icons>
          </view>
        </view>
        <view class="pop_info" @tap="genderDialogToggle">
          <view class="title">
            <uni-icons type="staff" size="25" color="#cb4f20"></uni-icons>
            <text>性别</text>
          </view>
          <view class="info_text">

            <text>{{info.gender?"女":"男"}}</text>
            <uni-icons type="forward" size="15" color="#bebebe"></uni-icons>
          </view>
        </view>
        <wangding-pickerAddress class="city" @change="adrComfirm">
          <view class="pop_info">
            <view class="title">
              <uni-icons type="location" size="25" color="#cb4f20"></uni-icons>
              <text>地区</text>
            </view>

            <view class="info_text">

              <text>{{info.province+" "+info.city+" "+info.district}}</text>
              <uni-icons type="forward" size="15" color="#bebebe"></uni-icons>
            </view>

          </view>
        </wangding-pickerAddress>

       

        <view class="pop_info" @tap="goGift">
          <view class="title">
            <uni-icons type="gift" size="25" color="#cb4f20"></uni-icons>
            <text>待兑换礼物</text>
          </view>
        </view>
        <view class="pop_info" @tap="goOrder">
          <view class="title">
            <uni-icons type="wallet" size="25" color="#cb4f20"></uni-icons>
            <text>兑换订单管理</text>
          </view>
        </view>
        <view class="pop_info" @tap="goAddress">
          <view class="title">
            <uni-icons type="location" size="25" color="#cb4f20"></uni-icons>
            <text>收货地址管理</text>
          </view>
        </view>

        <view class="pop_info" @tap="adminScan" v-if="info.role==1">
          <view class="title">
            <uni-icons type="auth" size="25" color="#cb4f20"></uni-icons>
            <text>管理员扫码兑换礼品</text>
          </view>
        </view>
        <view class="pop_info" @tap="goAdminPost">
          <view class="title">
            <uni-icons type="wallet" size="25" color="#cb4f20"></uni-icons>
            <text>管理员发货</text>
          </view>
        </view>
        <!--        <uni-collapse>
          <uni-collapse-item titleBorder="none">
            <template v-slot:title>
              <view class="pop_info">
                <view class="title">
                  <uni-icons type="gift" size="25" color="#cb4f20"></uni-icons>
                  <text>待兑换礼物</text>
                </view>
              </view>
            </template>


            <uni-list>

              <uni-list-item class="giftList" v-for="(item, index) in giftList" :key="index" :title="item.gift">
                <template v-slot:footer>

                  <div class="exchange_btn" @tap="qrDialogToggle(item)" v-if="item.status=='WAITING_COLLECT'"> 兑换</div>
                  <div class="exchange_btn" v-if="item.status=='FINISH'"> 已兑换</div>
                </template>
              </uni-list-item>

            </uni-list>


          </uni-collapse-item>
        </uni-collapse> -->

        <!-- <view class="pop_info" @tap="generateCdk" v-if="info.role==1">
          <view class="title">
            <uni-icons type="auth" size="25" color="#cb4f20"></uni-icons>
            <text>管理员生成打卡验证码</text>
          </view>
        </view> -->

        <view class="pop_info" @tap="openToken">
          <view class="title">
            <uni-icons type="auth" size="25" color="#cb4f20"></uni-icons>
            <text>查看token</text>
          </view>
        </view>

      </view>



      <!-- <view class="uni-padding-wrap uni-common-mt"> -->

    </view>

    <!-- </view> -->



    <!-- 输入框示例 -->
    <uni-popup ref="nameDialog" type="dialog">


      <uni-popup-dialog title="修改昵称" type="info" @confirm="nameConfirm">
        <uni-easyinput v-model="infotemp.nickname" maxlength="8" placeholder="请输入姓名" />
      </uni-popup-dialog>
    </uni-popup>

    <!-- 输入框示例 -->
    <uni-popup ref="genderDialog" type="dialog">


      <uni-popup-dialog title="修改性别" type="info" @confirm="genderConfirm">
        <uni-data-checkbox v-model="infotemp.gender" :localdata="genders" />
      </uni-popup-dialog>
    </uni-popup>
    <!-- 礼物 -->
    <!--  <uni-popup ref="giftDialog" background-color="#fff" type="dialog">

      <view class="giftList">
        <uni-list class="giftList">

          <uni-list-item v-for="(item, index) in giftList" :key="index" :title="item.gift_name">
            <template v-slot:footer>

              <div class="exchange_btn"  @tab="exchange(item)">兑换</div>
            </template>
          </uni-list-item>

        </uni-list>
      </view>
    </uni-popup> -->

    <!-- 二维码弹窗 -->

    <uni-popup ref="qrDialog" background-color="#fff" type="dialog" @change="checkCdk">

      <view class="qrDialog">

        <!-- ref 后续保存到相册会用到 options配置项 @press长按二维码回调函数 -->
        <!-- <w-qrcode ref="qrcode" :options="options" @press="longtap"></w-qrcode> -->
        <w-qrcode v-if ref="qrcode" :options="qrOptions"></w-qrcode>
      </view>
    </uni-popup>



    <!-- 管理员确认兑换 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog :type="info" cancelText="关闭" confirmText="确定" title="兑换用户礼品" :content="alertContent"
        @confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
    </uni-popup>

    <!-- 管理员生成打卡验证码 -->
    <uni-popup ref="punchCodeDialog" background-color="#fff" type="dialog">
      <view class="popup-content">
        <view class="punchCode">
          {{punchCode}}

          <!-- <uni-icons type="reload" size="30" color="#cb4f20" @click="refreshCdk"></uni-icons> -->

        </view>


        <view class="center" @click="refreshCdk">
          <view class="exchange_btn">
            刷新验证码
          </view>


        </view>
      </view>
    </uni-popup>

    <uni-popup ref="tokenDialog" type="dialog">
      <view class="token">
        <text selectable>{{token}}</text>
      </view>
    </uni-popup>



    </uni-popup>
    <view>
      <!-- 输入框示例 -->
      <uni-popup ref="loginDialog" type="dialog">
        <uni-popup-dialog title="请设置个人信息" type="info" confirmText="确定" @confirm="loginConfirm">
          <view>
            <view class="flex_center"><text>头像：</text>
              <button open-type="chooseAvatar" style="margin: 0px 10px;" class="top_box_info_picdiv_pic"
                @chooseavatar="uploadPorTemp">
                <image :src="infotemp.avatarUrl" class="refreshIcon"></image>
              </button>
            </view>

            <view class="flex_center"><text>昵称：</text><uni-easyinput type="nickname" v-model="infotemp.nickname"
                maxlength="8" placeholder="请输入昵称" /></view>
            <view class="flex_center"> <text>性别：</text><uni-data-checkbox v-model="infotemp.gender"
                :localdata="genders" />
            </view>


            <wangding-pickerAddress class="city" @change="adrTemp">

              <view class="flex_center">

                <text>地区：</text>


                <view class="info_text">

                  <text>{{infotemp.province?infotemp.province+" "+infotemp.city+" "+infotemp.district:"选择地区"}}</text>

                </view>
              </view>

            </wangding-pickerAddress>

          </view>


        </uni-popup-dialog>

      </uni-popup>



    </view>
  </view>
</template>

<script>
  import top from "@/components/top.vue"
  import {
    putUserInfo,
    getUserInfo,
    uploadFile,
    getQrImg,
    getOwnList,
    cdkcheck,
    giftExchange,
    getGiftExchange,
    getCdk,
    getFileUrl
  } from "@/api/home.js"

  import {
    deepClone
  } from "@/utils/utils.js"
  export default {
    components: {
      top
    },
    data() {
      return {
        qrImg: "",
        punchCode: "",
        cdkid: "",
        alertContent: "",
        info: {
          nickname: "肖神农",
          gender: "",
          address: "上海 上海市 杨浦区"
        },
        infotemp: {
          nickname: "",
          gender: "",
          province: "",
          city: "",
          district: "",
          avatarUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"

        },
        grade: 0,
        giftList: [{
          gift: "可领取礼物",
          cdk: '兑换码'
        }, {
          gift: "可乐",
          cdk: '45357'
        }, {
          gift: "咖啡",
          cdk: '45154'
        }, {
          gift: "芬达",
          cdk: '45337'
        }],
        // 单选数据源
        genders: [{
          text: '男',
          value: 0
        }, {
          text: '女',
          value: 1
        }],
        portrait: "https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/logo.PNG",
        top_box_logo: "https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/logo_with_name.PNG",

        qrOptions: {
          code: '', // 生成二维码的值
          size: 460, // 460代表生成的二维码的宽高均为460rpx
          // img:{}

        },
        // 首次登录昵称姓名,
        inputDialog: true,
        token: ''
      }
    },
    onLoad() {
      if (wx.getStorageSync('is_new'))
        this.$refs.loginDialog.open();
      this.getUserInfo();
      this.getGiftList();
      this.videoContext = uni.createVideoContext('myVideo');
      this.getGrade()
    },

    methods: {
      getGrade() {
        this.grade = wx.getStorageSync('shenai_userAssetsInfo').grade || 0;
      },
      videoErrorCallback(e) {
        uni.showModal({
          content: e.target.errMsg,
          showCancel: false
        })
      },
      getUserInfo() {
        getUserInfo().then(res => {
          this.info = res.data.data;

          if (this.info.avatarUrl)
            this.portrait = this.info.avatarUrl;
          wx.setStorageSync('shenai_userInfo', this.info)

        });
      },
      async uploadPor(e) {
        let res = e.detail.avatarUrl;
        console.log("e.detail.avatarUrl", res);
        let urlres = await uploadFile(res);
        await putUserInfo({
          avatarUrl: urlres
        });
        this.getUserInfo();
        this.prePageRefresh();


      },
      async uploadPorTemp(e) {
        let res = e.detail.avatarUrl;
        console.log("e.detail.avatarUrl", res);
        this.infotemp.avatarUrl = await uploadFile(res);
      },
      prePageRefresh() {
        // let pages = getCurrentPages(); // 当前页面栈
        // let prePage = pages[pages.length - 2]; // 上一个页面

        // prePage.$vm.needRefresh = true;
        //更新home
        uni.$emit('homeRefresh', true)
        // 更新top
        uni.$emit('needRefresh', true);

      },
      qrDialogToggle(item) {
        this.qrOptions.code = item.cdk;
        this.cdkid = item.id;
        this.$refs.qrDialog.open();
      },
      nameDialogToggle() {
        this.infotemp = deepClone(this.info);
        console.log(this.infotemp.nickname)
        this.$refs.nameDialog.open();


      },
      getGiftList() {
        getOwnList().then(res => {
          console.log("getOwnList")
          console.log(res.data.data);
          this.giftList = res.data.data
          // this.$refs.giftDialog.open();
        });


      },
      change(data) {

        this.city = data.data.join('')
        console.log(data.data.join(''))
        console.log(this.city);
      },
      genderDialogToggle() {
        this.infotemp = deepClone(this.info);
        console.log(this.infotemp.name)
        this.$refs.genderDialog.open();


      },


      checkCdk(e) {
        // this.openQrDialog = e.show;
        if (!e.show) {
          cdkcheck(this.cdkid).then(res => {
            console.log(res.data.data);
            if (res.data.data.status == 'FINISH') {
              setTimeout(() => {
                uni.showToast({
                  title: `您已成功兑换${res.data.data.gift}`,
                  icon: 'none'
                });
              }, 1000)

              this.getGiftList();
              this.prePageRefresh();
            }
          })
        }
      },

      adrComfirm(data) {
        let province = data.data[0];
        if (province.indexOf("内蒙古") != -1) {
          province = province.substr(0, 3)
        } else if (province.indexOf("区") != -1) {
          province = province.substr(0, 2)
        } else {
          province = province.replace("省", "");
          province = province.replace("市", "");
        }
        let adr = {
          province: province,
          city: data.data[1],
          district: data.data[2]
        }
        putUserInfo(adr).then(res => {
          this.getUserInfo();
          this.prePageRefresh();
        })



      },
      adrTemp(data) {
        let province = data.data[0];
        if (province.indexOf("内蒙古") != -1) {
          province = province.substr(0, 3)
        } else if (province.indexOf("区") != -1) {
          province = province.substr(0, 2)
        } else {
          province = province.replace("省", "");
          province = province.replace("市", "");
        }
        this.infotemp.province = province;
        this.infotemp.city = data.data[1];
        this.infotemp.district = data.data[2];

        console.log("infotemp======", this.infotemp)
      },
      nameConfirm() {
        if (this.infotemp.nickname)
          putUserInfo({
            nickname: this.infotemp.nickname
          }).then(res => {
            this.getUserInfo();
            this.prePageRefresh();
          })
      },
      genderConfirm() {

        putUserInfo({
          gender: this.infotemp.gender
        }).then(res => {
          this.getUserInfo();
          this.prePageRefresh();
        })
      },
      adminScan() {
        var that = this;
        // 只允许通过相机扫码
        uni.scanCode({
          onlyFromCamera: true,
          success: function(res) {
            console.log('条码类型：' + res.scanType);
            console.log('条码内容：' + res.result);

            getGiftExchange(res.result).then(res => {

              that.alertContent =
                // `确定给用户“${res.data.data.user}”兑换“${res.data.data.gift}”?${res.data.data.is_delete ? "(此礼品库存已被删除)" : ""}`;
                `确定兑换“${res.data.data.gift}”`;
              that.orderId = res.data.data.id;
              that.$refs.alertDialog.open()

            })

          }
        });
      },
      dialogConfirm() {
        //传orderid
        giftExchange(this.orderId).then(res => {
          if (res.data.code == 0)
            uni.showToast({
              title: `兑换成功`,
              icon: 'none'
            });

        })
      },
      generateCdk() {
        getCdk().then(res => {

          this.punchCode = res.data.data.cdk;
          this.$refs.punchCodeDialog.open();
        })
      },

      refreshCdk() {
        getCdk().then(res => {

          this.punchCode = res.data.data.cdk;
        })
      },

      loginConfirm() {
        if (this.infotemp.avatarUrl ==
          'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
          )
          this.infotemp.avatarUrl = "";
        putUserInfo(this.infotemp).then(res => {
          this.getUserInfo();
          this.prePageRefresh();
          uni.switchTab({
            url: "/pages/home/home",
            animationType: 'pop-in',
            animationDuration: 200
          })

        })

      },
      goGift() {
        uni.navigateTo({
          url: '/subpkg-home/gift/gift'
        })
      },
      goAddress() {
        uni.navigateTo({
          url: '/subpkg-home/address/address'
        })
      },
      goOrder() {

        uni.navigateTo({
          url: '/subpkg-home/order/order'
        })

      },
      goAdminPost() {

        uni.navigateTo({
          url: '/subpkg-home/adminPost/adminPost'
        })

      },
      openToken() {
        this.token = wx.getStorageSync('shenai_userToken').token;

        this.$refs.tokenDialog.open();
      },
      removeSto() {

        wx.clearStorageSync();
        uni.reLaunch({
          url: '/pages/login/login'
        });
      },


    }
  }
</script>

<style lang="scss">
  .top_box {}

  .top_box_info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    background-color: white;
    padding: 60rpx;
  }

  .top_box_info_picdiv {
    position: relative;
    display: flex;
  }



  .top_box_info_picdiv_pic {
    height: 100rpx;
    width: 100rpx;
    border-radius: 50%;
    border: 2rpx solid
  }

  button::after {
    border: none;
  }

  .refreshIcon {
    height: 100rpx;
    width: 100rpx;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 50%;
  }


  .top_box_info_picdiv_level {
    background-color: #ff7f6a;
    width: 80rpx;
    height: 27rpx;
    margin-top: -25rpx;
    border-radius: 15rpx;
    position: relative;
    font-size: 20rpx;
    color: white;
    text-align: center;
    left: 10rpx;
    top: 0px;

  }

  .top_box_info_name {
    margin-left: 30rpx;
    margin-top: 15rpx;
  }

  .top_box_info_name_text {
    font-weight: bold;
  }

  .top_box_info_name_loc {
    margin-left: 30rpx;
    font-size: 20rpx;
    color: #999999;
  }

  .top_box_info_name_date {
    margin-top: 10rpx;
    font-size: 25rpx;
    color: #999999;
  }

  .top_box_number {
    border-style: dashed hidden hidden hidden;
    border-color: #d3d3d3;
    border-width: 1rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20rpx;
    height: 85rpx;


  }

  .top_box_number_div {
    font-size: 28rpx;
    color: #999999;
    padding: 20rpx;
  }

  .info_box {
    width: 620rpx;
    margin-top: 20rpx;
    background-color: white;
    padding: 0rpx 60rpx;
  }

  .pop_info {

    font-size: 26rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #eeeeee;

  }

  .popup-content {
    padding: 30px;

    .punchCode {
      font-size: 50px;

      width: 130px;
      margin-bottom: 10px;
      text-align: center;
    }
  }

  .title {
    display: flex;
    align-items: center;

    text {
      margin-left: 10px;
      color: #999999;
    }
  }

  .info_text {
    display: flex;
    align-items: center;

    text {
      margin-left: 10px;
      color: #333333;
    }
  }

  .container {

    height: 100vh;
  }

  .center {

    display: flex;
    justify-content: center;

    // border: 1px solid red;
  }

  .giftList {
    color: #999 // width: 60vw;
      // min-height: 60vh;
      // max-height: 60vh;
      // margin-left: 20px;
  }

  .uni-list-item__content-title {
    color: #666 !important;
    margin-left: 30px !important;
  }

  .exchange_btn {
    border-radius: 3px;
    border: 1px solid #bdbdbd;
    padding: 4px 19px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    color: #666;
    font-size: 12px;
  }

  .qrDialog {
    height: 290px;
    width: 290px;
    border-radius: 8px;
    align-items: center;
    display: flex;
    justify-content: center;
  }

  .uni-popup__wrapper {
    padding: 0 !important;
  }

  .uni-collapse-item__title-arrow {
    margin-right: 0 !important;
  }

  .uni-border-top-bottom {
    max-height: calc(100vh - 414px);
    overflow-y: auto;
  }

  .video {
    align-items: center;
    display: flex;
    justify-content: center;
  }

  .flex_center {
    display: flex;
    flex-direction: row;
    // justify-content: center;
    align-items: center;
    padding: 10px 20px;

    text {
      color: #909399;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .token {
    background-color: white;
    height: 200px;
    width: 200px;
    word-wrap: break-word;
    padding: 20px;
    border-radius: 12px;
  }
</style>